import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";
// 别名 {} props解构出来
const PrivateRoute = ({ component: Component, user, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => {
        // 如果user存在 去想去的页面
        if (user) {
          return <Component {...props}></Component>;
        } else {
          return (
            // 不存在 打回登录页
            <Redirect
              to={{
                pathname: "/login",
                state: {
                  redirect: props.match.url
                }
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
};

export default connect(state => ({
  user: state.user
}))(PrivateRoute);
